<!-- src/pages/shop/shop.vue -->
<template>
    <view class="relative flex flex-col h-screen bg-gray-100">
        <!-- 搜索栏 -->
        <view class="p-4 bg-white shadow-md">
            <u-search placeholder="搜索商品" v-model="searchKeyword" @search="onSearch" class="bg-gray-200 rounded-full" />
        </view>

        <!-- 主要内容区域 -->
        <scroll-view scroll-y class="flex-1 overflow-y-auto" @scrolltolower="loadMore">
            <!-- 轮播图 -->
            <swiper class="h-40 mb-4" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
                <swiper-item v-for="(banner, index) in banners" :key="index">
                    <image :src="banner.image" mode="aspectFill" class="w-full h-full" />
                </swiper-item>
            </swiper>

            <!-- 商品分类 -->
            <view class="p-4 mb-4 bg-white rounded-lg">
                <view class="mb-2 text-lg font-bold">商品分类</view>
                <view class="grid grid-cols-5 gap-2">
                    <view v-for="category in categories" :key="category.id" class="flex flex-col items-center">
                        <image :src="category.icon" mode="aspectFit" class="w-12 h-12 mb-1 rounded-full" />
                        <text class="text-xs text-center">{{ category.name }}</text>
                    </view>
                </view>
            </view>

            <!-- 热门商品 -->
            <view class="p-4 bg-white rounded-lg">
                <view class="mb-2 text-lg font-bold">热门商品</view>
                <view class="grid grid-cols-2 gap-4">
                    <view v-for="product in hotProducts" :key="product.id"
                        class="overflow-hidden bg-white rounded-lg shadow" @click="navigateToDetail(product)">
                        <image :src="product.image" mode="aspectFill" class="object-cover w-full h-32" />
                        <view class="p-2">
                            <text class="text-sm font-medium line-clamp-2">{{ product.name }}</text>
                            <view class="flex items-center justify-between mt-1">
                                <text class="font-bold text-red-500">¥{{ product.price }}</text>
                                <u-button size="mini" type="primary"
                                    @click.stop="addToCartHandler(product)">加入购物车</u-button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 加载更多 -->
            <u-loadmore :status="loadMoreStatus" />

            <!-- 悬浮购物车按钮 -->
            <view class="fixed z-50 bottom-40 right-4">
                <image src="@/static/images/icon/car-icon.png" class="w-12 h-12 rounded-full shadow-lg"
                    @click="navigateToCart" />
                <view v-if="cartItemCount > 0"
                    class="absolute flex items-center justify-center w-5 h-5 text-xs bg-red-500 rounded-full -top-2 -right-2">
                    {{ cartItemCount }}</view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getIndex, type Product, addToCart, getCartItems, type CartItem } from '@/api/shop'

interface Banner {
    image: string
}

interface Category {
    id: number
    name: string
    icon: string
}

const searchKeyword = ref('')
const banners = ref<Banner[]>([])
const categories = ref<Category[]>([])
const hotProducts = ref<Product[]>([])
const page = ref(1)
const loadMoreStatus = ref<'loadmore' | 'loading' | 'nomore'>('loadmore')

const onSearch = () => {
    console.log('Searching for:', searchKeyword.value)
    // 实现搜索逻辑
}

const navigateToDetail = (product) => {
    uni.navigateTo({
        url: '/pages/shop/product_detail',
        success: (res) => {
            res.eventChannel.emit('productData', product)
        }
    })
}

const addToCartHandler = async (product: Product) => {
    await addToCart(product)
    await refreshCartItems()
    uni.showToast({
        title: '已加入购物车',
        icon: 'success'
    })
}

const refreshCartItems = async () => {
    cartItems.value = await getCartItems()
}

const fetchData = async () => {
    try {
        loadMoreStatus.value = 'loading'
        const indexData = await getIndex()
        banners.value = indexData.banners
        categories.value = indexData.categories
        hotProducts.value = indexData.hotProducts
        loadMoreStatus.value = 'nomore' // 因为我们只有一页数据
    } catch (error) {
        console.error('Failed to fetch shop data:', error)
        loadMoreStatus.value = 'loadmore'
    }
}

const loadMore = () => {
    if (loadMoreStatus.value === 'loadmore') {
        fetchData()
    }
}

const navigateToCart = () => {
    uni.navigateTo({
        url: '/pages/shop/cart'
    })
}

onMounted(async () => {
    console.log('Shop homepage mounted')
    await fetchData()
    await refreshCartItems()
})

onShow(async () => {
    console.log('Shop page shown')
    await refreshCartItems()
})

// 添加购物车商品数量计算
const cartItems = ref<CartItem[]>([])
const cartItemCount = computed(() =>
    cartItems.value.reduce((total, item) => total + item.quantity, 0)
)
</script>

<style scoped>
.cart-button {
    width: 60px !important;
    height: 60px !important;
    border-radius: 30px !important;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    background-color: #ff6b6b !important;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.car-icon {
    width: 32px;
    height: 32px;
}

.cart-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background-color: #feca57;
    color: #ffffff;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
}
</style>
